import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store/index'

Vue.use(VueRouter)

//路由导航冗余报错(路由重复)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    name: 'manage',
    component: () => import('../views/Manage'),
    meta: { auth: true },   // 设置当前路由需要校验
    redirect: '/home',
    children: [{
        path: '/home',
        name: 'home',
        component: () => import('../views/home/Home'),
        meta: { affix: true, noCache: true }
      },{
        path: '/project',
        name: 'project',
        component: () => import('../views/project/details/Project'),
      },{
        path: '/create',
        name: 'create',
        component: () => import('../views/project/details/Create'),
      },{
        path: '/remember',
        name: 'remember',
        component: () => import('../views/project/details/Remember'),
      },{
      path: '/search',
      name: 'search',
      component: () => import('../views/project/Search')
    },{
      path: '/merits',
      name: 'merits',
      component: () => import('../views/merits/Merits')
    },{
      path: '/user',
      name: 'user',
      component: () => import('../views/user/User')
    }]
  },{
    path: '/login',
    name: 'login',
    component: () => import('../views/Login'),
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//提供一个重置路由的方法
export const resetRouter = () => {
  router.matcher = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
  })
}

//全局解析守卫
// router.beforeResolve(async to => {
//   if (to.meta.requiresCamera) {
//     try {
//       await askForCameraPermission()
//     } catch (error) {
//       if (error instanceof NotAllowedError) {
//         // ... 处理错误，然后取消导航
//         return false
//       } else {
//         // 意料之外的错误，取消导航并把错误传给全局处理器
//         throw error
//       }
//     }
//   }
// })

// 前置路由守卫
router.beforeEach(((to, from, next) => {
  if (to.matched.some(m => m.meta.auth)){
    if (store.state.isLogin === store.state.currentUser){   //将当前登录的用户名和授权用户比对
      next()
    }else {
      //未登录则跳转到登陆界面
      next({ path:'/login' } )
    }
  }else {
    next()
  }
}))
// router.beforeEach(async (to,from,next) => {
//   if (this.store.currentMenu !== null){
//     next({ name:'Login' })
//   }
//   else{
//     next()
//   }
// })

export default router
